package queue;

/**
 * 作业2： 不使用size，浪费一个空间
 *
 * @param <E>
 */
public class LoopQueue3<E> implements Queue<E> {
    private E[] data;
    private int front, tail;

    /**
     * 因为我们有意识地浪费了一个空间，所以真实的容量是用户传来的容量+1
     *
     * @param capacity
     */
    public LoopQueue3(int capacity) {
        data = (E[]) new Object[capacity + 1];
        front = 0;
        tail = 0;
    }

    public LoopQueue3() {
        this(10);
    }

    public int getCapacity() {
        return data.length - 1;
    }

    /**
     * @param e
     */
    @Override
    public void enqueue(E e) {
        if ((tail + 1) % data.length == front) resize(getCapacity() * 2);
        data[tail] = e;
        tail = (tail + 1) % data.length;//必须使用data.length
    }

    /**
     * 重置数组容量
     * (i + front) % data.length  表示从零开始的索引
     *
     * @param newCapacity 重置数组容量
     */
    private void resize(int newCapacity) {
        E[] newData = (E[]) new Object[newCapacity + 1];
        int sz = getSize();
        for (int i = 0; i < sz; i++) {
            newData[i] = data[(i + front) % data.length];
        }
        data = newData;
        front = 0;
        tail = sz;
    }

    @Override
    public E dequeue() {
        if (isEmpty())
            throw new IllegalArgumentException("Cannot dequeue from an empty queue.");

        E ret = data[front];
        data[front] = null;
        front = (front + 1) % data.length;
        if (getSize() == getCapacity() / 4 && getCapacity() / 2 != 0)
            resize(getCapacity() / 2);
        return ret;
    }

    @Override
    public E getFont() {
        if (isEmpty()) throw new IllegalArgumentException("Cannot getFront from an empty queue");
        return data[front];
    }

    @Override
    public int getSize() {
        return tail - front >= 0 ? tail - front : tail + (data.length - front);
    }

    @Override
    public boolean isEmpty() {
        return front == tail;
    }

    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        res.append(String.format("Queue: size = %d ,capacity= %d\n", getSize(), getCapacity()));
        res.append("front [");
        for (int i = front; i != tail; i = (i + 1) % data.length) {
            res.append(data[i]);
            if ((i + 1) % data.length != tail) {
                res.append(",");
            }
        }
        res.append("] tail");
        return res.toString();

    }

    public static void main(String[] args) {

        Queue<Integer> queue = new LoopQueue3<>();
        for (int i = 0; i < 10; i++) {
            queue.enqueue(i);
            System.out.println(queue);

            if (i % 3 == 2) {
                queue.dequeue();
                System.out.println(queue);
            }
        }
    }
}
